package com.zoe.wan.android.example.fragment.home

import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.zoe.wan.android.example.BR
import com.zoe.wan.android.example.R
import com.zoe.wan.android.example.activity.webview.WebActivity
import com.zoe.wan.android.example.common.adapter.HomeListAdpter
import com.zoe.wan.android.example.databinding.FragmentHomeBinding
import com.zoe.wan.base.BaseFragment

class FragHome : BaseFragment<FragmentHomeBinding, FragHomeViewModel>() {

    private val adpter = HomeListAdpter()
    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun getViewModelId(): Int {
        return BR.homeVm
    }

    override fun initViewData() {
        initListView()

        observerData()

        refreshOrLoadMore()


    }

    private fun refreshOrLoadMore() {

        // 下拉刷新
        binding?.homeRefreshView?.setOnRefreshListener {
            viewModel?.initData() {
                it.finishRefresh()
            }
        }

        // 上拉加载
        binding?.homeRefreshView?.setOnLoadMoreListener {
            viewModel?.initData(true) {
                it.finishLoadMore()
            }
        }
    }

    private fun observerData() {
        viewModel?.list?.observe(viewLifecycleOwner) { list ->
            list?.let {
                adpter.setData(it)
            }
        }
        viewModel?.bannerItem?.observe(viewLifecycleOwner) { item ->
            item?.let {
                adpter.setBannerData(it)
            }
        }
    }

    private fun initListView() {
        binding?.homeListView?.layoutManager = LinearLayoutManager(context)
        binding?.homeListView?.adapter = adpter
        adpter.registerListener(object : HomeListAdpter.HomeItemCollectListener {


            override fun itemCollect(id: String, position: Int) {
                viewModel?.collect(id) {
                    adpter.setCollect(position)
                }
            }

            override fun itemClick(title: String, link: String) {
                jumpWeb(title, link)
            }

            override fun bannerClick(title: String, link: String) {
                jumpWeb(title, link)
            }
        })
    }

    fun jumpWeb(title: String, link: String) {
        val intent = Intent(context, WebActivity::class.java)
        intent.putExtra(WebActivity.INTENT_WEB_TITLE_KEY, title)
        intent.putExtra(WebActivity.INTENT_WEB_URL_KEY, link)
        startActivity(intent)

    }
}